package com.simon.dao;

import java.util.List;

import android.content.Context;
import android.util.Log;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.QueryBuilder;
import com.simon.notes.model.NotesModel;

public class NoteRepository {
	private static final long ONE_DAY = 86400000;
	private NoteDaoHelper db;
	Dao<NotesModel, Integer> noteModelDao;

	public NoteRepository(Context ctx) {
		try {
			DatabaseManager dbManager = new DatabaseManager();
			db = dbManager.getHelper(ctx);
			noteModelDao = db.getMyNoteDao();
		} catch (java.sql.SQLException e) {
			Log.e(NoteRepository.class.getName(), e.getMessage());
			e.printStackTrace();
		}

	}

	public int create(NotesModel noteModel) {
		try {
			return noteModelDao.create(noteModel);
		} catch (java.sql.SQLException e) {
			Log.e(NoteRepository.class.getName(), e.getMessage());
			e.printStackTrace();
		}
		return 0;
	}

	public int update(NotesModel noteModel) {
		try {
			return noteModelDao.update(noteModel);
		} catch (java.sql.SQLException e) {
			Log.e(NoteRepository.class.getName(), e.getMessage());
			e.printStackTrace();
		}
		return 0;
	}

	public int delete(NotesModel noteModel) {
		try {
			return noteModelDao.delete(noteModel);
		} catch (java.sql.SQLException e) {
			Log.e(NoteRepository.class.getName(), e.getMessage());
			e.printStackTrace();
		}
		return 0;
	}

	public List<NotesModel> getAll() {
		try {
			return noteModelDao.queryForAll();
		} catch (java.sql.SQLException e) {
			Log.e(NoteRepository.class.getName(), e.getMessage());
			e.printStackTrace();
		}
		return null;
	}

	public NotesModel findById(Integer id) {

		try {
			noteModelDao.queryForId(id);
		} catch (java.sql.SQLException e) {
			Log.e(NoteRepository.class.getName(), e.getMessage());
			e.printStackTrace();
		}
		return null;
	}

	public List<NotesModel> findByTopic(String topic) {
		try {
			QueryBuilder<NotesModel, Integer> queryBuilder = noteModelDao
					.queryBuilder();

			if (topic.equals("")) {
				return noteModelDao.queryForAll();
			} else {
				return queryBuilder.where().like(NotesModel.TOPIC, "%"+topic+"%")
						.query();
			}
		} catch (java.sql.SQLException e) {
			Log.e(NoteRepository.class.getName(), e.getMessage());
			e.printStackTrace();
		}
		return null;
	}
}
